using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.Services;
using System.Text.RegularExpressions;

public partial class Pages_Employee_ManageDeliveries_EditDelivery : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Request.QueryString["id"] != null)
            {
                BindFields();
                FillFields();
            }
            else
                Response.Redirect("ViewDeliveries.aspx");
        }
    }

    // getting items for drop down lists
    private void BindFields()
    {
        Service[] services = DALService.ListService().ToArray();
        foreach (Service s in services)
        {
            ddlService.Items.Add(new ListItem(s.ServiceName, s.ServiceID));
        }
        Distance[] distances = DALDistance.GetDistances().ToArray();
        foreach (Distance d in distances)
        {
            ddlDistance.Items.Add(new ListItem(d.Description, d.DistanceID.ToString()));
        }
        City[] cities = DALCity.ListCity().ToArray();
        foreach (City c in cities)
        {
            ddlReceiverCity.Items.Add(new ListItem(c.CityName, c.CityID));
        }
    }

    private void FillFields()
    {
        try
        {
            int id = Int32.Parse(Request.QueryString["id"].ToString());
            List<Deliverable> list = DALDeliverable.GetDeliverablesByDeliverableID(id);
            if (list.Count < 1)
                Response.Redirect("~/Errors/ConnectionError.aspx");

            // fill the fields with information in the Deliverable object
            Deliverable deliverable = list[0];
            txtDeliverableID.Text = deliverable.DeliverableID.ToString();
            txtCustomerID.Text = deliverable.CustomerID.ToString();
            ddlType.Text = deliverable.Type;
            ddlService.ClearSelection();
            ddlService.Items.FindByText(deliverable.ServiceName).Selected = true;
            txtWeight.Text = deliverable.Weight.ToString();
            ddlDistance.ClearSelection();
            ddlDistance.Items.FindByText(deliverable.Distance).Selected = true;
            cboStatus.Checked = deliverable.Status;
            txtReceiverName.Text = deliverable.ReceiverName;
            txtReceiverAddress.Text = deliverable.ReceiverAddress;
            ddlReceiverCity.ClearSelection();
            ddlReceiverCity.Items.FindByText(deliverable.ReceiverCity).Selected = true;
        }
        catch (FormatException ex)
        {
            Response.Redirect("~/Errors/GeneralError.aspx");
        }
        catch (SqlException ex)
        {
            Response.Redirect("~/Errors/ConnectionError.aspx");
        }
        catch (Exception ex)
        {
            Response.Redirect("~/Errors/GeneralError.aspx");
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid) return;

        // getting field values
        int id = Int32.Parse(txtDeliverableID.Text);
        int customerID = Int32.Parse(txtCustomerID.Text);
        string type = ddlType.SelectedItem.Text;
        int serviceID = Int32.Parse(ddlService.SelectedValue);
        float weight = float.Parse(txtWeight.Text);
        int distanceID = Int32.Parse(ddlDistance.SelectedValue);
        bool status = cboStatus.Checked;
        string receiverName = txtReceiverName.Text.Trim();
        string receiverAddress = txtReceiverAddress.Text.Trim();
        int receiverCityID = Int32.Parse(ddlReceiverCity.SelectedValue);

        int affected;
        try
        {
            affected = DALDeliverable.UpdateDeliverable(id, customerID, type, serviceID, weight, distanceID, status, receiverName, receiverAddress, receiverCityID);
            if (affected > 0)
                lblMessage.Text = "Edited successfully";
            else
                lblMessage.Text = "Error editing deliverable";
        }
        catch
        {
            lblMessage.Text = "Error editing deliverable. Please note that customer ID must exists.";
        }
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        FillFields();
        lblMessage.Text = "";
        txtCustomerID.Focus();
    }

    // checks whether the customer ID is a positive integer > 0
    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        try
        {
            int n = Int32.Parse(txtCustomerID.Text);
            args.IsValid = (n > 0);
        }
        catch (FormatException ex)
        {
            args.IsValid = false;
        }
    }

    // Checks whether the weight field is a positive float number > 0
    protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
    {
        try
        {
            float n = float.Parse(txtWeight.Text);
            args.IsValid = (n > 0);
        }
        catch (FormatException ex)
        {
            args.IsValid = false;
        }
    }

    /// <summary>
    /// This webmethod checks whether a customer ID is existed
    /// </summary>
    /// <param name="id">id</param>
    /// <returns>1 if the parameter is an id of an existed customer, 0 otherwise, -1 if id string is not a valid id</returns>
    [WebMethod]
    public static int IsExistedID(string id)
    {
        Regex idPattern = new Regex("^[1-9][0-9]*$");
        if (!idPattern.IsMatch(id))
            return -1;
        int n = Int32.Parse(id);
        if (DALCustomers.GetCustomersByID(n).Count != 0)
            return 1;
        else
            return 0;
    }
}
